package cn.always.xiajia.admin.sys.controller.pc;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xingyuv.captcha.model.common.ResponseModel;
import com.xingyuv.captcha.model.vo.CaptchaVO;
import com.xingyuv.captcha.service.CaptchaService;

import cn.always.xiajia.framework.common.util.ExtServletUtil;
import cn.always.xiajia.framework.mybatis.core.controller.BaseControllerX;
import cn.hutool.core.util.StrUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

@Tag(name = "管理后台-验证码")
@RestController
@RequestMapping("/admin/sys/syscaptcha")
@Slf4j
public class SysCaptchaController extends BaseControllerX {

	@Resource
	protected CaptchaService captchaService;

	@PostMapping({ "/get" })
	@Operation(summary = "获得验证码")
	@PermitAll
	public ResponseModel get(@RequestBody CaptchaVO data, HttpServletRequest request) {
		assert request.getRemoteHost() != null;
		data.setBrowserInfo(getRemoteId(request));
		return captchaService.get(data);
	}

	@PostMapping("/check")
	@Operation(summary = "校验验证码")
	@PermitAll
	public ResponseModel check(@RequestBody CaptchaVO data) {
		data.setBrowserInfo(getRemoteId(request));
		return captchaService.check(data);
	}

	public static String getRemoteId(HttpServletRequest request) {
		// 获取客户端IP
		String ip = ExtServletUtil.getClientIP(request);
		String ua = request.getHeader("user-agent");
		if (StrUtil.isNotBlank(ip)) {
			return ip + ua;
		}
		return request.getRemoteAddr() + ua;
	}

}
